package com.xql.framework.util;


import com.xql.framework.action.ActionMapping;
import com.xql.framework.action.Result;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.Element;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by apple on 15/3/22.
 */
public class ReadXML {
    public static Map<String,ActionMapping>  getElements(String xmlPath){
        Map<String,ActionMapping> map = new HashMap<String, ActionMapping>();
        Document doc = null;
        try{
            // 读取并解析XML文档
            // SAXReader就是一个管道，用一个流的方式，把xml文件读出来
            //
            SAXBuilder reader =new SAXBuilder();
            doc = reader.build(new File(xmlPath));
            Element root =  doc.getRootElement();
            Element actions = root.getChild("actions");
            List<Element> actiones = actions.getChildren();
            ActionMapping actionMapping = null;
            for(Element action :actiones){
                actionMapping = new ActionMapping();
                actionMapping.setName(action.getAttributeValue("name"));
                actionMapping.setActionClass(action.getAttributeValue("class"));
                actionMapping.setMethod(action.getAttributeValue("method"));
               List<Element> results = action.getChildren();
                Result rs = null;
                for(Element result:results){
                    rs = new Result();
                    rs.setName(result.getAttributeValue("name"));
                    rs.setPath(result.getText());
                    boolean flag = result.getAttributeValue("isRedirect")==""?false:Boolean.parseBoolean(result.getAttributeValue("isRedirect"));
                    rs.setRedirect(flag);
                    actionMapping.addResult(rs.getName(),rs);
                }
                map.put(actionMapping.getName(),actionMapping);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        }

        return map;
    }

}
